<?php

namespace App\Http\Controllers\Buy;

use App\Library\Mall\OrderCreator;
use App\Models\Cart;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class OrderController extends BaseController
{
    public function confirmOrder()
    {
        $items = $this->request->input('items');
        if ($items) {
            $shoplist = [];
            $totalFee = 0;
            DB::table('cart as c')->leftJoin('item as i', 'i.itemid', '=', 'c.itemid')
                ->whereIn('i.itemid', $items)->select(['c.quantity', 'c.shop_name', 'i.*'])->get()
                ->map(function ($item) use (&$shoplist, &$totalFee){
                    $shop[] = [];
                    if (!isset($shoplist[$item->shop_id])) {
                        $shop = [
                            'shop_id'=>$item->shop_id,
                            'shop_name'=>$item->shop_name,
                            'items'=>[],
                            'order_fee'=>0,
                            'shipping_fee'=>0,
                            'total_fee'=>0,
                        ];
                    } else {
                        $shop = $shoplist[$item->shop_id];
                    }

                    $item->simple_total = formatAmount($item->price*$item->quantity);
                    $shop['order_fee']+= $item->simple_total;
                    $shop['shipping_fee']+= $item->shipping_fee;
                    $shop['total_fee']+= $item->price * $item->quantity;
                    $shop['items'][$item->itemid] = get_object_vars($item);
                    $shoplist[$item->shop_id] = $shop;

                    $totalFee+= $item->simple_total+$item->shipping_fee;
                });

            $this->assign(compact('shoplist', 'totalFee'));
            return $this->view('buy.confirm_order');
        } else {
            return $this->showError(trans('ui.invalid_parameter'));
        }
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
     * @throws \Exception
     */
    public function createOrder()
    {
        $address_id    = $this->request->post('address_id');
        $pay_type      = $this->request->post('pay_type');
        $shipping_type = $this->request->post('shipping_type');
        $buyer_message = $this->request->post('buyer_message');

        $items = $this->request->post('items');
        $shops = Cart::with(['items'=>function($query){
            return $query->where('uid', $this->uid);
        }])->where('uid', $this->uid)->whereIn('itemid', $items)->groupBy('shop_id')->get(['shop_id','shop_name']);

        foreach ($shops as $shop) {
            $creator = new OrderCreator();
            $creator->shop  = $shop->shop;
            $creator->items = $shop->items;
            $creator->addressId = $address_id;
            $creator->payType = $pay_type;
            $creator->shippingType = $shipping_type;
            $creator->buyerMessage = $buyer_message[$shop->shop_id];

            try {
                $creator->createOrder();
            } catch (\Exception $e){

            }
        }
        //清空购物车
        Auth::user()->cartItems()->whereIn('itemid', $items)->delete();
        return redirect('/user/trade/bought');
    }
}
